package com.ruoyi.kanfang.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.kanfang.domain.BuildingInfo;
import com.ruoyi.kanfang.mapper.BuildingInfoMapper;
import com.ruoyi.kanfang.service.IBuildingInfoService;
import com.ruoyi.kanfang.util.JsoupConstant;
import com.ruoyi.kanfang.util.JsoupUtils;
import com.ruoyi.kanfang.util.KanFangUrl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 楼盘小区Service业务层处理
 * 
 * @author limin
 * @date 2024-04-28
 */
@Slf4j
@Service
public class BuildingInfoServiceImpl implements IBuildingInfoService
{
    @Resource
    private BuildingInfoMapper buildingInfoMapper;

    /**
     * 查询楼盘小区
     * 
     * @param id 楼盘小区主键
     * @return 楼盘小区
     */
    @Override
    public BuildingInfo selectBuildingInfoById(Long id)
    {
        return buildingInfoMapper.selectBuildingInfoById(id);
    }

    /**
     * 查询楼盘小区列表
     * 
     * @param buildingInfo 楼盘小区
     * @return 楼盘小区
     */
    @Override
    public List<BuildingInfo> selectBuildingInfoList(BuildingInfo buildingInfo)
    {
        return buildingInfoMapper.selectBuildingInfoList(buildingInfo);
    }

    /**
     * 新增楼盘小区
     * 
     * @param buildingInfo 楼盘小区
     * @return 结果
     */
    @Override
    public int insertBuildingInfo(BuildingInfo buildingInfo)
    {
        return buildingInfoMapper.insertBuildingInfo(buildingInfo);
    }

    /**
     * 修改楼盘小区
     * 
     * @param buildingInfo 楼盘小区
     * @return 结果
     */
    @Override
    public int updateBuildingInfo(BuildingInfo buildingInfo)
    {
        return buildingInfoMapper.updateBuildingInfo(buildingInfo);
    }

    /**
     * 批量删除楼盘小区
     * 
     * @param ids 需要删除的楼盘小区主键
     * @return 结果
     */
    @Override
    public int deleteBuildingInfoByIds(Long[] ids)
    {
        return buildingInfoMapper.deleteBuildingInfoByIds(ids);
    }

    /**
     * 删除楼盘小区信息
     * 
     * @param id 楼盘小区主键
     * @return 结果
     */
    @Override
    public int deleteBuildingInfoById(Long id)
    {
        return buildingInfoMapper.deleteBuildingInfoById(id);
    }

    @Override
    public AjaxResult initData(Integer dataSource) {
        try{
            Integer maxPage = 15;
            for(int i = 1;i<=maxPage;i++){
                String url = String.format(KanFangUrl.KF_BEIKE_BUILDING_URL,i);
                // 连接网页并获取HTML文档
                Document doc = Jsoup.connect(url).get();
                // 解析HTML并获取标题
                String title = doc.title();
                // 打印标题
                System.out.println("Title: " + title);
                //获取小区列表 <ul class="listContent" log-mod="list">
                Date date = new Date();
                Element element = doc.selectFirst("ul.listContent");
                List<BuildingInfo> list = new ArrayList<>();
                if(element != null){
                    Elements liList = element.select("li");
                    for(int j=0;j<liList.size();j++) {
                        Element li = liList.get(j);
                        // 小区名称
                        String name = JsoupUtils.getText(li.selectFirst("div.title a.maidian-detail"));
                        // 小区详情页链接
                        String buildingDetail = JsoupUtils.getAttr(li.selectFirst("div.title a.maidian-detail"), JsoupConstant.ATTR_HREF);
                        // 90天内成交量
                        String atitle = StringUtils.join(name, "网签");
                        String day90Sell = JsoupUtils.getText(li.selectFirst("div.houseInfo a[title=" + atitle + "]"));
                        Long day90SellInt = getSellingCount(day90Sell);
                        // 在租数量
                        String rentTitle = StringUtils.join(name, "租房");
                        String rentCount = JsoupUtils.getText(li.selectFirst("div.houseInfo a[title=" + rentTitle + "]"));
                        // 所属区 大区
                        String area = JsoupUtils.getText(li.selectFirst("div.positionInfo a.district"));
                        // 所属区细分
                        String areaDetail = JsoupUtils.getText(li.selectFirst("div.positionInfo a.bizcircle"));
                        // 小区年代
                        String years = JsoupUtils.getOwnText(li.selectFirst("div.positionInfo"));
                        // 在售数量
                        String sellingCount = JsoupUtils.getText(li.selectFirst("div.xiaoquListItemSellCount a.totalSellCount span"));
                        // 参考均价 averagePrice
                        String averagePrice = JsoupUtils.getText(li.selectFirst("div.xiaoquListItemPrice div.totalPrice span"));
                        String averagePriceNote = JsoupUtils.getText(li.selectFirst("div.xiaoquListItemPrice div.priceDesc"));
                        BuildingInfo build = new BuildingInfo();
                        build.setBuildingName(name);
                        build.setBuildingDetail(buildingDetail);
                        build.setCity("赣州");
                        build.setArea(area);
                        build.setAreaDetail(areaDetail);
                        build.setYears(years);
                        yearsDeal(build,years);
                        build.setDay90Sell(day90SellInt);
                        build.setAveragePrice(averagePrice);
                        build.setSource(1L);
                        build.setSellingCount(Long.valueOf(sellingCount));
                        build.setCreateTm(date);
                        build.setAveragePriceNote(averagePriceNote);
                        build.setRentCount(getRentCount(rentCount));
                        list.add(build);
                    }
                }
                //插入数据
                if(!CollectionUtils.isEmpty(list)){
                    list.forEach(item->{
                        //判断是否已存在
                        if(buildingInfoMapper.selectBuildingInfoByName(item.getBuildingName()) > 0){
                            log.info("【{}】小区数据已被收录",item.getBuildingName());
                            return;
                        }
                        buildingInfoMapper.insertBuildingInfo(item);
                    });
                }
            }
        }catch (Exception e){
            log.error("【{}】数据初始化失败",e);
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    private void yearsDeal(BuildingInfo build,String years){
        if(StringUtils.isNotBlank(years)){
            years = years.contains("年")?years.replace("年",""):years;
            years = years.contains("/")?years.replace("/",""):years;
            years = years.contains(" ")?years.replace(" ",""):years;
            build.setYears(years);
            if(years.contains("-")){
                String[] split = years.split("-");
                if(split.length == 2){
                    Long startYear = NumberUtils.isNumber(split[0]) ? Long.valueOf(split[0]):0;
                    Long endYear = NumberUtils.isNumber(split[1]) ? Long.valueOf(split[1]):0;
                    build.setStartYear(startYear);
                    build.setEndYear(endYear);
                }
            }else{
                Long startYead = NumberUtils.isNumber(years) ? Long.valueOf(years):0;
                build.setStartYear(startYead);
            }
        }
    }
    private Long getSellingCount(String sellingCount){
        if(StringUtils.isNotBlank(sellingCount)){
            //90天成交0套 截取出数字
            String count = StringUtils.substringBetween(sellingCount,"成交","套");
            return NumberUtils.isNumber(count) ? Long.valueOf(count):0;
        }
        return 0L;
    }

    private Long getRentCount(String rentCount){
        if(StringUtils.isNotBlank(rentCount)){
            //90天成交0套 截取出数字
            String count = StringUtils.substringBefore(rentCount,"套");
            return NumberUtils.isNumber(count) ? Long.valueOf(count):0L;
        }
        return 0L;
    }
}
